package lock;

/**
 * Created by lizhenyu on 2019/9/23
 *
 * description 可重入锁简单实现
 */
public class ReEntryLock {

    Thread thread1;
    Thread thread2;
    Thread lockThread;

    int lockCount = 0;

    public ReEntryLock() {
        thread1 = new LockThread(1);
        thread2 = new LockThread(2);
    }

    public synchronized void lock() throws InterruptedException {
        Thread thread = Thread.currentThread();
        if(lockThread == null) {
            lockThread = thread;
        }
        if(lockCount >= 0 && thread.equals(lockThread)) {
            lockCount++;
            System.out.println(thread + "加锁" + lockCount);
        } else {
            System.out.println(thread + "将被阻塞");
            wait();
        }
    }

    public synchronized void unlock(){
        Thread thread = Thread.currentThread();
        if(lockCount > 0 && thread.equals(lockThread)) {
            lockCount--;
            System.out.println(thread + "解锁" + lockCount);
            if(lockCount == 0) {
                lockThread = null;
                System.out.println(thread + "唤醒阻塞线程");
                notify();
            }
        }
    }

    class LockThread extends Thread {
        int second;
        LockThread(int second) {
            this.second = second;
        }
        @Override
        public void run() {
            try {
                while (true) {
                    lock();
                    lock();
                    sleep(second * 1000);
                    unlock();
                    unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ReEntryLock test = new ReEntryLock();
        test.thread1.start();
        test.thread2.start();
    }
}
